use std::process::{Command, Stdio};
use crate::local_history::entry::TimelineEntry;

pub fn get_git_history(path: &str) -> Result<Vec<TimelineEntry>, String> {
    if path.is_empty() {
        return Ok(vec![]);
    }

    let mut cmd = Command::new("git");
    cmd.args(&[
        "log",
        "--oneline",
        "--pretty=format:%H|%s|%an|%ct",
        "--max-count=50",
        "--",
        path,
    ]);
    
    cmd.stdout(Stdio::piped())
       .stderr(Stdio::piped());

    let output = match cmd.output() {
        Ok(output) => output,
        Err(e) => {
            return Err(format!("Failed to execute git command: {}", e));
        }
    };

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!("Git command failed: {}", stderr));
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut commits = Vec::new();

    for line in stdout.lines() {
        if line.trim().is_empty() {
            continue;
        }

        let parts: Vec<&str> = line.split('|').collect();
        if parts.len() >= 4 {
            let timestamp = parts[3].parse::<i64>().unwrap_or(0) * 1000; // convert to milliseconds
            commits.push(TimelineEntry {
                id: parts[0].to_string(),
                message: parts[1].to_string(),
                author: if parts[2].is_empty() { None } else { Some(parts[2].to_string()) },
                timestamp,
                source: "Git".to_string(),
            });
        }
    }

    Ok(commits)
}

#[tauri::command]
pub fn get_git_history_content(path: &str, id: &str) -> Result<String, String> {
    let mut cmd = Command::new("git");
    cmd.args(&["show", &format!("{}:{}", id, path)]);

    let output = match cmd.output() {
        Ok(output) => output,
        Err(e) => {
            return Err(format!("Failed to execute git command: {}", e));
        }
    };

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!("Git command failed: {}", stderr));
    }

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    Ok(stdout)
}